package com.adong.service.impl;

import com.adong.dao.BookDao;
import com.adong.dao.OrderDao;
import com.adong.dao.OrderItemDao;
import com.adong.dao.imlp.BookDaoImpl;
import com.adong.dao.imlp.OrderDaoImpl;
import com.adong.dao.imlp.OrderItemDaoImpl;
import com.adong.pojo.*;
import com.adong.service.OrderService;
import com.sun.org.apache.xpath.internal.operations.Or;

import java.util.Date;
import java.util.Map;

/**
 * @author adong
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();

    /**
     * @param cart   购物车对象
     * @param userId 用户的id
     * @return 返回的订单号
     */
    @Override
    public String createOrder(Cart cart, Integer userId) {
        //订单号
        String orderId = System.currentTimeMillis() + "" + userId;
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);
        //保存订单
        orderDao.saveOrder(order);
        //遍历购物车中的每一个商品项转换成订单项保存到数据库中
        for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {
            //获取购物车中的商品项,转换成订单项
            CartItem cartItem = entry.getValue();
            OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalPrice(), orderId);
            //将订单项保存到数据库中
            orderItemDao.saveOrderItem(orderItem);
            Book book = bookDao.queryBookById(cartItem.getId());
            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock() - cartItem.getCount());
            bookDao.updateBook(book);
        }
        cart.clear();
        return orderId;
    }
}
